package com.gexiaobao.pigeon.ui.fragment.mine.pigeon

import android.app.Dialog
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.bean.PigeonFosterBean
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentShedPigeonBasicInfoBinding
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityForceAnalysis
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityShedAddPigeon
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 17:15
 * @Describe    : 寄养基本信息
 */
class FragmentShedPigeonBasicInfo : BaseFragment<MyPigeonViewModel, FragmentShedPigeonBasicInfoBinding>() {

    private var imgList: ArrayList<String> = arrayListOf()
    private lateinit var mPigeonData: PigeonBean.RingInfo
    private var mPigeonId: String = ""
    private var mFeatherColorId: Int = 0

    override fun initView(savedInstanceState: Bundle?) {
        mFeatherColorId = requireArguments().getInt("featherColorId")
        mPigeonId = requireArguments().getString("pigeonId").toString()
        showLoading(getString(R.string.loading))
        mViewModel.getPigeonInfo(mPigeonId.toInt())

        eventViewModel.toModifyPigeonResult.observeInFragment(this) {
            showLoading(getString(R.string.loading))
            mViewModel.getPigeonInfo(it)
        }
    }

    override fun onStart() {
        super.onStart()
        mDatabind.banner.start()
    }

    override fun onStop() {
        super.onStop()
        mDatabind.banner.stop()
    }

    private fun showUIData(mPigeonData: PigeonBean.RingInfo) {
        if (mPigeonData.bodyPicPath.isEmpty() && mPigeonData.featherPicPath.isEmpty() && mPigeonData.rightHeadPicId.isEmpty() && mPigeonData.leftHeadPicPath.isEmpty()) {
            mDatabind.banner.visibility = View.GONE
        } else {
            imgList.clear()
            if (mPigeonData.bodyPicPath.isNotEmpty()) {
                imgList.add(mPigeonData.bodyPicPath)
            }
            if (mPigeonData.featherPicPath.isNotEmpty()) {
                imgList.add(mPigeonData.featherPicPath)
            }
            if (mPigeonData.rightHeadPicId.isNotEmpty()) {
                imgList.add(mPigeonData.rightHeadPicId)
            }
            if (mPigeonData.leftHeadPicPath.isNotEmpty()) {
                imgList.add(mPigeonData.leftHeadPicPath)
            }
        }
        mDatabind.banner.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(imgList)).setIndicator(CircleIndicator(context))
            .setLoopTime(5000).setOnBannerListener { data, _ ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast(getString(R.string.the_image_resource_fail))
                    return@setOnBannerListener
                }
                bigImageLoader(data.toString())
            }
        mDatabind.banner.setBannerRound(20F)
        mDatabind.tvShedFeatherColor.text = mPigeonData.featherColorStr
        when (mPigeonData.sex) {
            1 -> {
                mDatabind.tvShedDetailSex.text = (getString(R.string.hint_unknown))
            }

            2 -> {
                mDatabind.tvShedDetailSex.text = (getString(R.string.hint_female))
            }

            3 -> {
                mDatabind.tvShedDetailSex.text = (getString(R.string.hint_male))
            }
        }
        when (mPigeonData.eyePattern) {
            1 -> {
                mDatabind.tvShedDetailEyePattern.text = (getString(R.string.hint_unknown))
            }

            2 -> {
                mDatabind.tvShedDetailEyePattern.text = (getString(R.string.pigeon_yellow))
            }

            3 -> {
                mDatabind.tvShedDetailEyePattern.text = (getString(R.string.pigeon_sha))
            }

            4 -> {
                mDatabind.tvShedDetailEyePattern.text = (getString(R.string.pigeon_bull))
            }
        }
    }

    private fun bigImageLoader(url: String) {
        Thread {
            val bitmap = Util.netToLoacalBitmap(url)
            val message = Message()
            message.obj = bitmap
            mHandler.sendMessage(message)
        }.start()
    }

    private var mHandler = Handler {
        if (it.obj == null) {
            RxToast.showToast(getString(R.string.the_image_resource_fail))
        } else {
            val bitmap: Bitmap = it.obj as Bitmap
            showBigImage(bitmap)
        }
        false
    }

    private fun showBigImage(bitmap: Bitmap) {
        val dialog = activity?.let { Dialog(it) }
        val image = ImageView(context)
        image.setImageBitmap(bitmap)
        dialog?.setContentView(image)
        //将dialog周围的白块设置为透明
        dialog?.window?.setBackgroundDrawableResource(android.R.color.black)
        dialog?.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        dialog?.show()
        image.setOnClickListener {
            dialog?.cancel()
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvShedBasicInfoModify, mDatabind.tvShedBasicInfoDelete, mDatabind.tvDragging, mDatabind.tvShedBasicInfoDelete) {
            when (it) {
                mDatabind.tvShedBasicInfoDelete -> {
                    deletePigeon()
                }

                mDatabind.tvDragging -> {
                    try {
                        startActivity<ActivityForceAnalysis>(
                            "pigeonId" to mPigeonId,
                            "ringId" to mPigeonData.ringId,
                            "raceId" to 0,
                            "raceType" to 0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                mDatabind.tvShedBasicInfoModify -> {
                    startActivity<ActivityShedAddPigeon>("type" to 2, "pigeonData" to mPigeonData)
                }

                mDatabind.tvShedBasicInfoDelete -> {
                    deletePigeon()
                }
            }
        }
    }

    private fun deletePigeon() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.is_delete_this_pigeon))
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.deletePigeon(mPigeonId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取赛鸽详情 */
        mViewModel.pigeonInfoResult.observe(this) {
            mDatabind.data = it
            mPigeonData = it
            showUIData(it)
        }
        /** 删除赛鸽 */
        mViewModel.deletePigeon.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                activity?.finish()
                eventViewModel.toRefreshList.value = true
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    companion object {

        fun newInstance(pigeonId: String, featherColorId: Int): FragmentShedPigeonBasicInfo {
            val fragment = FragmentShedPigeonBasicInfo()
            val bundle = Bundle()
            bundle.putString("pigeonId", pigeonId)
            bundle.putInt("featherColorId", featherColorId)
            fragment.arguments = bundle
            return fragment
        }
    }
}